import configparser
import hashlib
import os

import langid
import requests
import pandas as pd
from core.dialog import Dialog
import random


class Application:
    __secretId = ''
    __secretKey = ''
    __configPath = os.path.expanduser(r"~\AppData\Roaming\EnglishScript\Config.ini")
    __url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'

    __englishFile = None
    dictLang = {
        'auto': 'auto',
        'zh': 'zh',
        'en': 'en',
    }

    def __init__(self):
        base_dir = os.path.join(os.environ["APPDATA"], "EnglishScript")
        self.__configPath = os.path.join(base_dir, "Config.ini")
        os.makedirs(base_dir, exist_ok=True)
        open(self.__configPath, 'a').close()
        self.__initConfig()

    def __initConfig(self):
        config = configparser.ConfigParser()
        config.read(self.__configPath)
        if 'API' not in config:
            config['API'] = {}
            dictTemp = self.__showDialog()
            config['API']['id'] = dictTemp['id']
            config['API']['key'] = dictTemp['key']
            self.__secretId = dictTemp['id']
            self.__secretKey = dictTemp['key']
        else:
            self.__secretId = config['API']['id']
            self.__secretKey = config['API']['key']
        if 'English_Path' not in config:
            config['English_Path'] = {}
            config['English_Path']['Path'] = os.path.join(os.environ["APPDATA"], "EnglishScript", "English.xlsx")
            open(config['English_Path']['Path'], 'a').close()
        else:
            self.__englishPath = config['English_Path']['Path']
        try:
            self.__englishFile = pd.read_excel(self.__englishPath, index_col=False)
        except Exception:
            self.__englishFile = pd.DataFrame(columns=['中文', '英文'])

        with open(self.__configPath, 'w') as configfile:
            config.write(configfile)

    def __showDialog(self):
        dialog = Dialog()
        dialog.setModal(True)
        dialog.show()
        dialog.exec()
        return dialog.getDialogInfo()

    def __translation(self, originalLang, targetLang, text):
        salt = random.randint(32768, 65536)
        sign_str = self.__secretId + text + str(salt) + self.__secretKey
        sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
        params = {
            'q': text,
            'from': self.dictLang[originalLang],
            'to': self.dictLang[targetLang],
            'appid': self.__secretId,
            'salt': salt,
            'sign': sign
        }
        resp = requests.get(self.__url, params=params).json()
        if 'trans_result' in resp:
            return resp['trans_result'][0]['dst']
        return '[翻译失败]'

    def save(self, text):
        if len(text.strip()) < 2:
            lang = 'en'
        else:
            lang, _ = langid.classify(text)
            if lang not in ('en', 'zh'):
                lang = 'en'
        from_lang = 'auto'
        to_lang = 'zh' if lang == 'en' else 'en'

        if lang == 'en':
            src_col, dst_col = '英文', '中文'
        else:
            src_col, dst_col = '中文', '英文'

        exists = self.__englishFile[self.__englishFile[src_col] == text]
        if not exists.empty:
            result = exists.iloc[0][dst_col]
            return str(result)
        translated = self.__translation(from_lang, to_lang, text).lower()
        new_row = pd.DataFrame([{src_col: text, dst_col: translated}])
        self.__englishFile = pd.concat([self.__englishFile, new_row], ignore_index=True)
        self.__englishFile.to_excel(self.__englishPath, index=False)
        return translated
    def openEnglishFile(self):
        os.startfile(self.__englishPath)
